<?php

class order {

  function beginOrderLoginForm (&$shop,$params) {
    $shop->out('<form action="'.$shop->getVar('SECURE_SCRIPT_NAME').'" target="'.$shop->cfgTplFrame['order_address'].'"><input type="hidden" name="a" value="cl"><input type="hidden" name="tr" value="'.$shop->getVar('TEMPLATE_ROOT').'"><input type="hidden" name="t" value="'.$shop->cfgTpl['order_address'].'">');
  }

  function beginOrderAddrForm (&$shop,$params) {
    $shop->out('<form action="'.$shop->getVar('SECURE_SCRIPT_NAME').'" target="'.$shop->cfgTplFrame['order_pay_supply'].'"><input type="hidden" name="a" value="cas"><input type="hidden" name="tr" value="'.$shop->getVar('TEMPLATE_ROOT').'"><input type="hidden" name="t" value="'.$shop->cfgTpl['order_pay_supply'].'">');
  }

  function beginOrderSelPayForm (&$shop,$params) {
    $shop->out('<form action="'.$shop->getVar('SECURE_SCRIPT_NAME').'" target="'.$shop->cfgTplFrame['order_cc_ba'].'"><input type="hidden" name="a" value="cp"><input type="hidden" name="tr" value="'.$shop->getVar('TEMPLATE_ROOT').'"><input type="hidden" name="t" value="'.$shop->cfgTpl['order_cc_ba'].'">');
  }

  function beginOrderPayForm (&$shop,$params) {
    $shop->out('<form action="'.$shop->getVar('SECURE_SCRIPT_NAME').'" target="'.$shop->cfgTplFrame['order_finish'].'">');
    if ($params[0]) $shop->out('<input type="hidden" name="cf" value="'.$params[0].'">');
    $shop->out('<input type="hidden" name="a" value="cf"><input type="hidden" name="tr" value="'.$shop->getVar('TEMPLATE_ROOT').'"><input type="hidden" name="t" value="'.$shop->cfgTpl['order_finish'].'">');
  }

  function beginOrderFinishForm (&$shop,$params) {
    $shop->out('<form action="'.$shop->getVar('SECURE_SCRIPT_NAME').'" target="'.$shop->cfgTplFrame['order_thanx'].'"><input type="hidden" name="a" value="on"><input type="hidden" name="tr" value="'.$shop->getVar('TEMPLATE_ROOT').'"><input type="hidden" name="t" value="'.$shop->cfgTpl['order_thanx'].'">');
  }

  function beginOrderiClearForm (&$shop,$params) {
    $shop->out('<form action="'.$shop->getVar('SCRIPT_NAME').'" target="'.$shop->cfgTplFrame['iclear_jump'].'"><input type="hidden" name="a" value="icb"><input type="hidden" name="tr" value="'.$shop->getVar('TEMPLATE_ROOT').'"><input type="hidden" name="t" value="'.$shop->cfgTpl['iclear_jump'].'">');
  }

  function endOrderForm (&$shop,$params = '') {
    $shop->out("</from>");
  }

  function orderCountrySelect (&$shop,$params) {
    if (!$this->countries) {
      $this->countries = $shop->call('dbacountries','getall');
    }
    $shop->out('<select name="'.$params[0].'">'."\n");
    if ($params[1]){
      $shop->out("<option value=\"\">".$params[1]."</option>\n");
    }
    preg_match("/\w+\[(.*)\]/",$params[0],$matches);
    $selected   = $shop->getVar('CUST_'.strtoupper($matches[1]));
    $shop->out("selected:".$selected);
    foreach ($this->countries As $c) {
       $shop->out('<option value="'.$c['country'].'"');
       if ($selected == $c['country']) {
         $shop->out(' selected');
       }
       $shop->out('>'.$c['country']."</option>\n");
    }
    $shop->out("</select>\n");
  }

  function isHomeCountry (&$shop,&$w_home,&$w_abroad) {
      if (!$this->countries) {
        $this->countries = $shop->call('dbacountries','getall');
      }
      if (!($cust_c = $shop->getVar('CUST_ORLAND'))){
        $cust_c = $shop->getVar('CUST_LAND');
      }
      for ($i=0;$i<count($this->countries);$i++){
        if ($this->countries[$i]['country'] == $cust_c) {
           $is_home = $this->countries[$i]['home'];
           if ($is_home == 'N'){
             $w_abroad = 'Y';
           } else {
             $w_home   = 'Y';
           }
           break;
        }
      }
  }

  function orderSupplierSelect (&$shop,$params) {
    if (!$this->suppliers) {
      if ($params[0] != 'iClear'){
       $this->isHomeCountry($shop,$w_home,$w_abroad);
      } else {
       $w_home = 'Y';
      }
      $this->suppliers = $shop->call('dbasupplier','getSuppliersByArea',$w_home,$w_abroad);
    }
    $selected = $shop->getVar('CUST_SUPPLIER');
    $shop->out('<select name="customer[supplier]">'."\n");
    foreach ($this->suppliers As $s) {
       $shop->out('<option value="'.$s['id'].'"');
       //if () {}
       $shop->out('>'.$s['name']."</option>\n");
    }
    $shop->out("</select>\n");
  }

  function orderPaymentSelect (&$shop,$params) {
    if (!$this->paymentModes){
      $this->isHomeCountry($shop,$w_home,$w_abroad);
      $this->paymentModes = $shop->call('dbaPaymentMode','getByArea',$w_home,$w_abroad);
    }
    $selected = $shop->getVar('CUST_PAYMENTMODE');
    $str ='<select name="customer[paymentmode]">'."\n";
    foreach ($this->paymentModes As $p) {
       $str .= '<option value="'.$p['id'].'"';
       if ($p['id'] == $selected) {
         $str .= " Selected";
       } elseif ($p['is_default'] == 'Y'){
         $str .= " Selected";
       }
       $str .= '>'.$p['descr']."</option>\n";
    }
    $str .= "</select>\n";
    $shop->out($str);
  }

  function orderSubmit (&$shop,$params) {
    $shop->out('<input type="'.$params[0].'" ');
    if ($params[0] == 'image') {
      $shop->out('src="'.$params[1].'" '.$params[2].'>');
    } else {
      $shop->out('value="'.$params[1].'" '.$params[2].'>');
    }
  }

  function iClearJumpLink (&$shop,$params) {
    global $shopsid;
    if (!$this->cart) $this->cart = $shop->getSessionVar('s_cart');
    $qs .= 'ShopID='.$shop->cfgiClearID.'&BasketID='.$shopsid.'&Currency='.$shop->call('currency','stdCurrency',$shop).'&Products=';
    for ($i=0;$i<count($this->cart);$i++) {
       $art = &$this->cart[$i];
       $qs .= urlencode($art['name']).'::'.urlencode($art['orderno']).'::'.urlencode($art['quantity']).'::'.urlencode($art['single_price']-$art['single_taxamount']).'::'.urlencode($art['single_price']).'::'.urlencode($art['tax']).':::';
       for ($j=0;$j<count($this->cart[$i]['cnfart']);$j++) {
          $cnf = &$this->cart[$i]['cnfart'][$j];
          $qs .= urlencode($cnf['name']).'::'.urlencode($cnf['orderno']).'::'.urlencode($art['quantity']).'::'.urlencode($cnf['price']-$cnf['taxamount']).'::'.urlencode($cnf['price']).'::'.urlencode($cnf['tax']).':::';
       }
    }
    $shop->out('<a href="http://www.iclear.de/servlet/UniversalBuyTool2?'.$qs.'" target="'.$shop->cfgTplFrame['iclear_jump'].'">'.$params[0].'</a>');
  }

  function beginiClearLink (&$shop,$params) {
    $shop->out('<a href="'.$shop->getVar('SCRIPT_NAME').'?tr='.$shop->getVar('TEMPLATE_ROOT').'&t='.$shop->cfgTpl['iclear_start'].'" target="'.$shop->cfgTplFrame['iclear_start'].'">'.$params[0].'</a>');
  }

  function initPaymentConst (&$shop){
    if (!$this->allPaymentModes){
      $this->allPaymentModes = $shop->call('dbaPaymentMode','getAll');
    }
    if (is_array($this->allPaymentModes) && !$this->PayConst){
      foreach ($this->allPaymentModes As $pm){
        if ($pm['id'] == $shop->getVar('CUST_PAYMENTMODE')) {
          $shop->setVar('PAY_'.strtoupper(preg_replace("/![\w_]/","",preg_replace("/-/","_",$pm['descr']))),true);
        }
      }
      $this->PayConst = true;
    }
  }

  function ccSelect (&$shop,$params) {
    if (!$this->creditcards){
      $this->creditcards = $shop->call('dbaCreditCard','getactivated');
    }
    $selected = $shop->getVar('CUST_CCINST');
    $str = '<select name="customer[ccinst]">'."\n";
    foreach ($this->creditcards As $c) {
       $str .= '<option value="'.$c['name'].'"';
       //if () {}
       $str .= '>'.$c['name']."</option>\n";
    }
    $shop->out($str."</select>\n");
  }

  // p1 : separator ; p2 : weitere html attribute
  function ccDateSelect (&$shop,$params) {
     $str  = "<select name=\"customer[ccmon]\" ".$params[1].">\n";
     for ($i=0;$i<12;$i++)
      $str .= "  <option>".($i+1)."</option>\n";
     $str .= "</select>".$params[0];
     $date = getdate(time());
     $str .= "<select name=\"customer[ccyear]\" ".$params[1].">\n";
     for ($i=$date["year"];$i<($date["year"]+11);$i++)
      $str .= "  <option>".($i)."</option>\n";
     $str .= "</select>";
     $shop->out($str);
  }

  // p1 : weitere html attribute
  function ccNumber (&$shop,$params){
    $shop->out('<input name="customer[ccnumber]" type="text" '.$params[0].'>');
  }

  // p1 : weitere html attribute
  function baInstitution (&$shop,$params){
    $shop->out('<input name="customer[bainst]" type="text" '.$params[0].'>');
  }

  // p1 : weitere html attribute
  function baNumber (&$shop,$params){
    $shop->out('<input name="customer[banumber]" type="text" '.$params[0].'>');
  }

  // p1 : weitere html attribute
  function baBLZ (&$shop,$params){
    $shop->out('<input name="customer[bablz]" type="text" '.$params[0].'>');
  }

  function initPaymentAmount (&$shop,$params = ''){
    if (!$this->selPaymentMode){
        $mode = $shop->getVar('CUST_PAYMENTMODE');
        $this->selPaymentMode = $shop->call('dbaPaymentMode','get',$mode);
    }
    $shop->setVar('paycost_amount',$this->selPaymentMode['amount']);
    $shop->setVar('paycost_tax',$this->selPaymentMode['tax']);
    $shop->setVar('paycost_percent',$this->selPaymentMode['percent']);
    $shop->setVar('paymentmode_name',$this->selPaymentMode['descr']);
  }

  function calcPostage(&$shop,$params = ''){
    $supp = $shop->getVar('CUST_SUPPLIER');
    if (!$this->postageTable){
        $this->postageTable = $shop->call('dbasupplier','getPostage', $supp);
    }
    if (!$this->supplier){
      $this->supplier = $shop->call('dbasupplier','getSupplierSF', $supp);
    }
    $totalPrice   = $shop->call('IsCart','totalPrice');
    $totalWeight  = $shop->call('IsCart','totalWeight');
    $totalPackets = $shop->call('IsCart','totalPackets');
    if ((count($this->postageTable) == 1) && ($this->postageTable[0]['amount'] == 0) && ($this->postageTable[0]['kg'] == 0)){
      $postage = $this->postageTable[0];
    } else {
     foreach ($this->postageTable As $pt){
       if (($pt['amount'] && ($pt['amount'] < $totalPrice)) || ($pt['kg'] && ($pt['kg'] < $totalWeight))){
        $postage = $pt['cost'];
        break;
       }
     }
    }
    $shop->setVar('postage',$postage);
    $shop->setVar('postage_tax',($postage*($this->supplier['tax']/100)));
  }

  function paymentCostTax(&$shop,$params){
    return ($params[0]*($shop->getVar('paycost_tax')/100));
  }

  // private: for sendreplymail
  function getTranslationArray($meta){
     preg_match('/content="(.*?)"/',$meta,$match);
     $pairs = split(",",$match[1]);
     foreach ($pairs As $p){
       list($name,$value) = split("=",$p);
       $trarr[trim($name)] = trim($value);
     }
     return $trarr;
  }

  function sendReplyMail(&$shop,$params = ''){
    $fname  = $shop->cfgSF['etc']."replymail/".$shop->cfgSF['lang_str']."_replymail.is";
    if (file_exists($fname)){
      $fp = fopen($fname,"r");
      while (!feof($fp)){
        $mailcode .= fgets($fp,500000);
      }
      fclose($fp);
    } else {
      return "loaderror";
    }
    if (preg_match('/<meta *name="translation".*?>/im',$mailcode,$matches)){
        $mailcode  = preg_replace('<'.$matches[0].'>',"",$mailcode);
        $trarr     = $this->getTranslationArray($matches[0]);
        $customer  = $shop->getSessionVar('customer');
        $s_cart    = $shop->getSessionVar('s_cart');
        $stc       = $shop->call('currency','stdCurrency');
        $fAddr     = $shop->call('format','set','<<<<<<<<<<<<<%1:  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<%2');
        $formatTop = $shop->call('format','set',">>>%1  >>>>>>>>>>>>%2  >>>>>%3   <<<<<<<<<<<<<<<<<<<%4    >>>>>>>>>>>%5  >>>>>>>>>>>>>%6");
        $format    = $shop->call('format','set',">>>%1  >>>>>>>>>>>>%2  >>>>>%3   <<<<<<<<<<<<<<<<<<<%4    >>>>>>>%5 >>>%6    >>>>>>>%7 >>>%8");
        $formatBot = $shop->call('format','set',"                           <<<<<<<<<<<<<<<<<<<%1                   >>>>>>>%2 >>>%3");

        if ($customer['firma'])
          $billaddress .= $fAddr->getln(array($trarr['firm'],$customer['firma']));
        $billaddress .= $fAddr->getln(array($trarr['name'],$customer['name']));
        $billaddress .= $fAddr->getln(array($trarr['firstname'],$customer['vorname']));
        $billaddress .= $fAddr->getln(array($trarr['street'],$customer['strasse']));
        $billaddress .= $fAddr->getln(array($trarr['ziptown'],$customer['plz']." ".$s_customer['ort']));
        $billaddress .= $fAddr->getln(array($trarr['country'],$customer['land']));

        if ($customer['orname']){
         if ($customer['orfirma'])
           $deliveryaddress .= $fAddr->getln(array($trarr['firm'],$customer['orfirma']));
         $deliveryaddress .= $fAddr->getln(array($trarr['name'],$customer['orname']));
         $deliveryaddress .= $fAddr->getln(array($trarr['firstname'],$customer['orvorname']));
         $deliveryaddress .= $fAddr->getln(array($trarr['street'],$customer['orstrasse']));
         $deliveryaddress .= $fAddr->getln(array($trarr['ziptown'],$customer['orplz']." ".$s_customer['orort']));
         $deliveryaddress .= $fAddr->getln(array($trarr['country'],$customer['orland']));
        }

        $completeorder .= $formatTop->getln(array($trarr['pos'],$trarr['orderno'],$trarr['quantity'],$trarr['descr'],$trarr['price'],$trarr['subtotal']));
        $completeorder .= $formatTop->genFill($formatTop->length,"-")."\n";
        for ($i = 0; $i < count($s_cart); $i++){
         $completeorder .= $format->getln(array($i+1,$s_cart[$i]['orderno'],$s_cart[$i]['quantity'],$s_cart[$i]['name'],$shop->call('currency','currencyStr',$s_cart[$i]['price']),$stc,$shop->call('currency','currencyStr',$s_cart[$i]['price']*$s_cart[$i]['quantity']),$stc));
        }
        $completeorder .= $format->genFill($format->length,"-")."\n";
        $completeorder .= $formatBot->getln(array($trarr['discount'],$shop->call('currency','currencyStr',$customer['paycost_amount']),$stc));
        $completeorder .= $formatBot->getln(array($trarr['postage'],$shop->call('currency','currencyStr',$customer['postage']),$stc));
        $completeorder .= $formatBot->getln(array($trarr['tax'],$shop->call('currency','currencyStr',$customer['tax_amount']),$stc));
        $completeorder .= $format->genFill($format->length,"-")."\n";
        $completeorder .= $formatBot->getln(array($trarr['subtotal'],$shop->call('currency','currencyStr',$customer['total_amount']),$stc));
        $completeorder .= $format->genFill(27," ").$format->genFill(49,"=")."\n";
        $mailcode = preg_replace('/<%= *\$bill_address *%>/im',$billaddress,preg_replace('/<%= *\$delivery_address *%>/im',$deliveryaddress,preg_replace('/<%= *\$complete_order *%>/im',$completeorder,preg_replace('/<%= *\$name *%>/im',$customer['name'],preg_replace('/<%= *\$firstname *%>/im',$customer['vorname'],$mailcode)))));
        if ($params[1]){ $trarr['subject'] .= "Date"; }
        if ($params[0]){
          mail($trarr['mailto'],$trarr['subject'],$mailcode,"From: $cfgReplymailfrom");
        } else {
          mail($customer["email"],$trarr['subject'],$mailcode,"From: $cfgReplymailfrom");
        }
     }
  }

  function closeOrder (&$shop,$params=''){
    global $shop_session;
    $c = &$shop_session['customer'];
    unset($c['ccinst']);
    unset($c['ccmon']);
    unset($c['ccyear']);
    unset($c['ccnumber']);
    unset($c['bainst']);
    unset($c['banumber']);
    unset($c['bablz']);
    unset($c['s_cart']);
  }

}

?>